<?php
	/**
	* Bill Manager - Change bill state
	* @author: trungdt
	* @since: Oct 22, 2011
	* @version: 1.0
	* 
	*  
	* Change logs
	*/
	if (!defined('EXPONENT')) exit('');

	if (!exponent_users_isLoggedIn())
		die();

	$have_permission=false;
	if (exponent_users_isAdmin() || exponent_permissions_check(array('administrate', "bill_management"),$loc))
		$have_permission=true;

	if ($have_permission && isset($_REQUEST['state']) && isset($_REQUEST['id']))
	{
		$id=intval($_REQUEST['id']);
		$state=intval($_REQUEST['state']);
		
		$goods_return=isset($_REQUEST['goods_return'])?intval($_REQUEST['goods_return']):0;

		$lang=exponent_lang_loadFile("modules/productsmodule/views/_Bill_Management.php");

		// get old state
		$bill=$db->selectObject("productsmodule_bills", "id = {$id}");

		$sql="UPDATE {$db->prefix}productsmodule_bills SET bill_state = {$state} WHERE id = {$id}";
		$db->sql($sql);
		productsmodule::__Bill_AddLogs("Bill state changes to ".$lang['bill_state_'.$state], $id);

		$can_send_mail=true;

		// cộng dồn tiền total purchase
		if (($state == 2) || 
			(($state == 3) && ($bill->bill_state == 4))
		   ) 
		{
			// cộng dồn tiền
			$customer=$db->selectObject("productsmodule_customerinfo", "user_id = {$bill->buyer_user_id}");
			$customer->total_purchase+=$bill->bill_total;
			$db->updateObject($customer,"productsmodule_customerinfo" );
			$currency=productsmodule::_GetCurrencyDefault(LANG,1);
			$bill_total=productsmodule::_GetCurrencyFormat($currency, $bill->bill_total);
			$total_purchase=productsmodule::_GetCurrencyFormat($currency, $customer->total_purchase);
			productsmodule::__Bill_AddLogs("Added {$bill_total} into total purchase log of user {$bill->buyer_user_name}. Now total purchase of {$bill->buyer_user_name} is {$total_purchase}", $id);
		}

		if ($state == 3) // send completed
		{
			// check out of stock
			$sql="SELECT {$db->prefix}productsmodule_products.* 
					FROM {$db->prefix}productsmodule_products 
					INNER JOIN {$db->prefix}productsmodule_bills_details 
					ON {$db->prefix}productsmodule_products.id = {$db->prefix}productsmodule_bills_details.product_id
					WHERE {$db->prefix}productsmodule_products.stock_remain < {$db->prefix}productsmodule_bills_details.product_quantity AND {$db->prefix}productsmodule_bills_details.bill_id = {$bill->id}";
			$oos=$db->selectObjectsBySql($sql);
			
			// out of stock, send email warning
			if (count($oos) > 0)
			{
				$can_send_mail=false;
				$oos_list="";
				foreach ($oos as $v)
				{
					if ($oos_list != "")
						$oos_list.=" , ";
					$oos_list.=$v->title ." (ID = {$v->id})";
				}
				
				// revert the old state
				$sql="UPDATE {$db->prefix}productsmodule_bills SET bill_state = {$bill->bill_state} WHERE id = {$id}";
				$db->sql($sql);
				
				productsmodule::__Bill_AddLogs("Warning: Not enough products remain on store to change state for this bill. List of products which are not enough: {$oos_list}", -1);
				productsmodule::__Bill_AddLogs("Warning: change state erorr. Please contact Admin for support", $id);
				
				// send mail to admin
				$subject="Warning: Not enough products remain on store to change state for bill #{$bill->id}";
				$content="Warning: Not enough products remain on store to change state for bill #{$bill->id}. List of products which are not enough: {$oos_list}. Please check the store. Request made at ".date('F j, Y, H:i:s',aboid_getCurrentTime()). " by ip address ".$_SERVER['REMOTE_ADDR'];
				productsmodule::SendMail($subject, $content);
				
				echo $lang['not_enough_goods'];
			}
			else
			{
				// continue change state: trù bớt các sản phẩm ra khỏi kho, coi như xuất kho
				$p_inbill=$db->selectObjects("productsmodule_bills_details", "bill_id = {$bill->id}");
				$st="";
				foreach ($p_inbill as $k=>$v)
				{
					$sql="UPDATE {$db->prefix}productsmodule_products SET stock_remain = stock_remain-{$v->product_quantity} WHERE id = {$v->product_id}";
					$db->sql($sql);
					//
					if ($st != "")
						$st.=" , ";
					$st.="{$v->product_name} (x{$v->product_quantity})";
				}
				productsmodule::__Bill_AddLogs("{$st} sent to {$bill->buyer_user_name}.", $id);
				productsmodule::__Bill_AddLogs("{$st} sent to {$bill->buyer_user_name}.", -1);
			}
		}
		// nếu đã thanh toán, nhưng giờ hủy, thì trừ tiền ra
		// có cộng dồn hàng vào ko?
		if ($state == 4 && ($bill->bill_state ==2 || $bill->bill_state ==3))
		{
			$customer=$db->selectObject("productsmodule_customerinfo", "user_id = {$bill->buyer_user_id}");
			$customer->total_purchase-=$bill->bill_total;
			$db->updateObject($customer,"productsmodule_customerinfo" );
			$currency=productsmodule::_GetCurrencyDefault(LANG,1);
			$bill_total=productsmodule::_GetCurrencyFormat($currency, $bill->bill_total);
			$total_purchase=productsmodule::_GetCurrencyFormat($currency, $customer->total_purchase);
			productsmodule::__Bill_AddLogs("Subtracted {$bill_total} from total purchase log of user {$bill->buyer_user_name} because bill has been canceled. Now total purchase of {$bill->buyer_user_name} is {$total_purchase}", $id);
			
			if ($goods_return == 1)
			{
				$p_inbill=$db->selectObjects("productsmodule_bills_details", "bill_id = {$bill->id}");
				foreach ($p_inbill as $k=>$v)
				{
					$sql="UPDATE {$db->prefix}productsmodule_products SET stock_remain = stock_remain+{$v->product_quantity} WHERE id = {$v->product_id}";
					$db->sql($sql);
				}
				productsmodule::__Bill_AddLogs("All products from bill #{$bill->id} has been returned back to store.", $id);
			}
		}


		if ($can_send_mail)
		{
			$subject="Notification: User {$user->firstname} {$user->lastname} ({$user->username}) changes bill #{$id} state to ".$lang['bill_state_'.$state];
			$content="Notification: User {$user->firstname} {$user->lastname} ({$user->username}) changed bill #{$id} state at ".date('F j, Y, H:i:s',aboid_getCurrentTime()).". New bill state has been set to ".$lang['bill_state_'.$state].".".($goods_return==1?" This request also inclued products return.":"No products return.")." This request sent from IP Address ".$_SERVER['REMOTE_ADDR'].". Thanks.";
			
			productsmodule::SendMail($subject,$content);
		} 
	}
	exponent_theme_setFlagAjaxAction(true);
?>
